﻿using Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    public partial class frm_client : Form
    {
        public frm_client()
        {
            InitializeComponent();
            Text = "客户端";
            init();
            init_socket();
        }

        TextBox tb_send = new TextBox();
        public void init()
        {
            StartPosition = FormStartPosition.CenterScreen;
            Width = 440;
            Height = 500;

            tb_send.Location = new Point(10, 10);
            tb_send.Multiline = true;
            tb_send.Height = 200;
            tb_send.Width = 400;
            Controls.Add(tb_send);

            Button btn_send = new Button();
            btn_send.Location = new Point(10, tb_send.Top + tb_send.Height + 10);
            btn_send.Text = "发送";
            btn_send.Click += Btn_send_Click;
            Controls.Add(btn_send);
        }

        SocketClient_Kenel s_client = new SocketClient_Kenel(new[] { "127.0.0.1", "9876" });
        public void init_socket()
        {
            s_client.Init();
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Thread.Sleep(1);
                    if (!s_client.q_rec.IsEmpty) //队列不为空则取出
                    {
                        s_client.q_rec.TryDequeue(out byte[] data);
                        //这里可以对data进行自定义协议的解析 或者像下面这样直接转成字符串 
                        string res = Encoding.UTF8.GetString(data);
                        if (!string.IsNullOrWhiteSpace(res))
                        { tb_send.Invoke(new Action(() => { tb_send.Text = res; })); }
                    }
                }
            }, TaskCreationOptions.LongRunning);

        }
        private void Btn_send_Click(object sender, EventArgs e)
        {
            s_client.Send(tb_send.Text);
        }
    }
}
